package org.jeecg.modules.xmss.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.util.StringUtil;
import org.jeecg.modules.xmss.entity.XmssTowns;
import org.jeecg.modules.xmss.service.IXmssTownsService;
import org.jeecg.modules.xmss.vo.XmssTownsPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @Description: 乡镇信息表-公众号标识
* @Author: jeecg-boot
* @Date:   2020-09-18
* @Version: V1.0
*/
@Api(tags="乡镇信息表-公众号标识")
@RestController
@RequestMapping("/xmss/xmssTowns")
@Slf4j
public class XmssTownsController {
   @Autowired
   private IXmssTownsService xmssTownsService;

   /**
    * 分页列表查询
    *
    * @param xmssTowns
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "乡镇信息表-公众号标识-分页列表查询")
   @ApiOperation(value="乡镇信息表-公众号标识-分页列表查询", notes="乡镇信息表-公众号标识-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(XmssTowns xmssTowns,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       QueryWrapper<XmssTowns> queryWrapper = QueryGenerator.initQueryWrapper(xmssTowns, req.getParameterMap());
       Page<XmssTowns> page = new Page<XmssTowns>(pageNo, pageSize);
       IPage<XmssTowns> pageList = xmssTownsService.page(page, queryWrapper);
       return Result.OK(pageList);
   }

   /**
    *   添加
    *
    * @param xmssTownsPage
    * @return
    */
   //@AutoLog(value = "乡镇信息表-公众号标识-添加")
   //@ApiOperation(value="乡镇信息表-公众号标识-添加", notes="乡镇信息表-公众号标识-添加")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody XmssTownsPage xmssTownsPage) {
       XmssTowns xmssTowns = new XmssTowns();
       BeanUtils.copyProperties(xmssTownsPage, xmssTowns);
       xmssTownsService.saveMain(xmssTowns);
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param xmssTownsPage
    * @return
    */
   //@AutoLog(value = "乡镇信息表-公众号标识-编辑")
   //@ApiOperation(value="乡镇信息表-公众号标识-编辑", notes="乡镇信息表-公众号标识-编辑")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody XmssTownsPage xmssTownsPage) {
       XmssTowns xmssTowns = new XmssTowns();
       BeanUtils.copyProperties(xmssTownsPage, xmssTowns);
       XmssTowns xmssTownsEntity = xmssTownsService.getById(xmssTowns.getId());
       if(xmssTownsEntity==null) {
           return Result.error("未找到对应数据");
       }
       xmssTownsService.updateMain(xmssTowns);
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "乡镇信息表-公众号标识-通过id删除")
   //@ApiOperation(value="乡镇信息表-公众号标识-通过id删除", notes="乡镇信息表-公众号标识-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       xmssTownsService.delMain(id);
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   //@AutoLog(value = "乡镇信息表-公众号标识-批量删除")
   //@ApiOperation(value="乡镇信息表-公众号标识-批量删除", notes="乡镇信息表-公众号标识-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.xmssTownsService.delBatchMain(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功！");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "乡镇信息表-公众号标识-通过id查询")
   @ApiOperation(value="乡镇信息表-公众号标识-通过id查询", notes="乡镇信息表-公众号标识-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       XmssTowns xmssTowns = xmssTownsService.getById(id);
       if(xmssTowns==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(xmssTowns);

   }

    /**
     * 通过登录的token查询当前哪个镇
     *
     * @param
     * @return
     */
    @AutoLog(value = "乡镇信息表-公众号标识-token查询")
    @ApiOperation(value="乡镇信息表-公众号标识-token查询", notes="乡镇信息表-公众号标识-token查询")
    @GetMapping(value = "/queryByToken")
    public Result<?> queryByToken() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isNotEmpty(sysUser.getRelTenantIds())){
            XmssTowns xmssTowns = xmssTownsService.getById(sysUser.getRelTenantIds());
            return Result.OK(xmssTowns);
        }else{
            return Result.OK(null);
        }

    }

    /**
     * 通过登录的token查询当前哪个镇
     *
     * @param
     * @return
     */
    @AutoLog(value = "公众号接口--乡镇信息表-publicOpenId查询")
    @ApiOperation(value="公众号接口--乡镇信息表-publicOpenId查询", notes="jqk乡乡镇信息表-publicOpenId查询")
    @GetMapping(value = "/queryByPublicOpenId")
    public Result<?> queryByPublicOpenId(String publicOpenId) {
        if(StringUtils.isNotEmpty(publicOpenId)){
            XmssTowns xmssTowns = xmssTownsService.selectTownsByPublicOpenId(publicOpenId);
            return Result.OK(xmssTowns);
        }else{
            return Result.OK("您没有权限");
        }

    }

    /**
     * 通过id查询
     *
     * @param
     * @return
     */
    @AutoLog(value = "乡镇信息表--通过公众号标识查询")
    @ApiOperation(value="乡镇信息表--通过公众号标识查询", notes="乡镇信息表--通过公众号标识查询")
    @GetMapping(value = "/queryByOpenId")
    public Result<?> queryByOpenId(@RequestParam(name="publicOpenId",required=true) String publicOpenId) {
        XmssTowns xmssTowns = xmssTownsService.selectTownsByPublicOpenId(publicOpenId);
        if(xmssTowns==null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(xmssTowns);

    }


    /**
     * 管理员添加提示时间
     *
     * @param
     * @return
     */
    @AutoLog(value = "管理员添加提示时间")
    @ApiOperation(value="管理员添加提示时间", notes="管理员添加提示时间")
    @GetMapping(value = "/addTime")
    public Result<?> addTime(@RequestParam(name="numberOfDays",required=true) Integer numberOfDays) {
       /* XmssTowns xmssTowns = xmssTownsService.selectTownsByPublicOpenId(publicOpenId);*/
        LoginUser sysUsers = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isNotEmpty(sysUsers.getRelTenantIds())) {
             XmssTowns getXmssTowns = new XmssTowns();
            getXmssTowns.setId(sysUsers.getRelTenantIds());
            getXmssTowns.setRemind(numberOfDays);
            xmssTownsService.updateById(getXmssTowns);

        }else{
            return Result.error("此账号下暂未分配镇");
        }
       /* if(xmssTowns==null) {
            return Result.error("未找到对应数据");
        }*/
        return Result.OK("操作成功");

    }






    /**
   * 导出excel
   *
   * @param request
   * @param xmssTowns
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, XmssTowns xmssTowns) {
     // Step.1 组装查询条件查询数据
     QueryWrapper<XmssTowns> queryWrapper = QueryGenerator.initQueryWrapper(xmssTowns, request.getParameterMap());
     LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //Step.2 获取导出数据
     List<XmssTowns> queryList = xmssTownsService.list(queryWrapper);
     // 过滤选中数据
     String selections = request.getParameter("selections");
     List<XmssTowns> xmssTownsList = new ArrayList<XmssTowns>();
     if(oConvertUtils.isEmpty(selections)) {
         xmssTownsList = queryList;
     }else {
         List<String> selectionList = Arrays.asList(selections.split(","));
         xmssTownsList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
     }

     // Step.3 组装pageList
     List<XmssTownsPage> pageList = new ArrayList<XmssTownsPage>();
     for (XmssTowns main : xmssTownsList) {
         XmssTownsPage vo = new XmssTownsPage();
         BeanUtils.copyProperties(main, vo);
         pageList.add(vo);
     }

     // Step.4 AutoPoi 导出Excel
     ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
     mv.addObject(NormalExcelConstants.FILE_NAME, "乡镇信息表-公众号标识列表");
     mv.addObject(NormalExcelConstants.CLASS, XmssTownsPage.class);
     mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("乡镇信息表-公众号标识数据", "导出人:"+sysUser.getRealname(), "乡镇信息表-公众号标识"));
     mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
     return mv;
   }

   /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
     Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
     for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
         MultipartFile file = entity.getValue();// 获取上传文件对象
         ImportParams params = new ImportParams();
         params.setTitleRows(2);
         params.setHeadRows(1);
         params.setNeedSave(true);
         try {
             List<XmssTownsPage> list = ExcelImportUtil.importExcel(file.getInputStream(), XmssTownsPage.class, params);
             for (XmssTownsPage page : list) {
                 XmssTowns po = new XmssTowns();
                 BeanUtils.copyProperties(page, po);
                 xmssTownsService.saveMain(po);
             }
             return Result.OK("文件导入成功！数据行数:" + list.size());
         } catch (Exception e) {
             log.error(e.getMessage(),e);
             return Result.error("文件导入失败:"+e.getMessage());
         } finally {
             try {
                 file.getInputStream().close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     return Result.OK("文件导入失败！");
   }

}
